package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

var DOWNLOADURL = "https://api.jisuapi.com/news/get?channel=CHANNEL&start=0&num=40&appkey=a5685e12f09d0f81"
var UPLOADURL = ""

type List struct {
	Title    string `json:"title"`
	Time     string `json:"time"`
	Src      string `json:"src"`
	Category string `json:"category"`
	Pic      string `json:"pic"`
	Content  string `json:"content"`
	URL      string `json:"url"`
	Weburl   string `json:"weburl"`
}

type Result struct {
	Channel string `json:"channel"`
	Num     int    `json:"num"`
	List    []List `json:"list"`
}

type AutoGenerated struct {
	Status int    `json:"status"`
	Msg    string `json:"msg"`
	Result `json:"result"`
}

// 下载数据
func download(url string) (list AutoGenerated, err error) {
	var data []byte

	if data, err = get(url); err != nil {
		return
	}
	list, err = jsonToStruct(data)
	return
}

// Get请求
func get(url string) (robots []byte, err error) {
	var resp *http.Response

	resp, err = http.Get(url)
	if err != nil {
		return robots, err
	}

	defer resp.Body.Close()

	robots, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return robots, err
	}

	return robots, nil
}

// POST请求
func post(data string) (err error) {
	var resp *http.Response
	var body []byte

	resp, err = http.Post(UPLOADURL, "application/x-www-form-urlencoded", strings.NewReader(data))
	if err != nil {
		return err
	}

	defer resp.Body.Close()

	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	// todo
	fmt.Println(body)

	return nil
}

// 将json转为结构体
func jsonToStruct(str []byte) (list AutoGenerated, err error) {
	if err = json.Unmarshal(str, &list); err != nil {
		return list, err
	}

	if list.Status != 0 {
		return list, errors.New(list.Msg)
	}

	return list, nil
}

// 将结构体转为json字符串
func structToJson(result Result) (data string, err error) {
	var bdata []byte

	if bdata, err = json.Marshal(result); err != nil {
		return data, err
	}

	return string(bdata), nil
}

// 操作
func todo(channel string) {
	var url, data string
	var err error
	var list AutoGenerated
	url = strings.Replace(DOWNLOADURL, "CHANNEL", channel, 1)
	if list, err = download(url); err != nil {
		returnErrs(err.Error())
		return
	}
	fmt.Println(channel, "............................下载成功............................")

	if data, err = structToJson(list.Result); err != nil {
		returnErrs(err.Error())
		return
	}

	if err = post(data); err != nil {
		returnErrs(err.Error())
		return
	}

	fmt.Println(channel, "............................上传成功............................")
}

func returnErrs(err string) {
	fmt.Println("出错了！！！ 原因： " + err)
}

func main() {
	var val string
	//var channels = []string{"头条", "新闻", "国内", "国际", "政治", "财经", "体育", "娱乐", "军事", "教育", "科技", "NBA", "股票", "星座", "女性", "健康", "育儿"}
	var channels = []string{"头条", "新闻"}
	for _, val = range channels {
		go todo(val)
	}
	time.Sleep(8 * time.Second)
}
